/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-07 21:54:55
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.controller;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.zlg.common.springmvc.validate.constraints.NotNull;
import com.joysuch.wwyt.bp.bean.BpSafetyStatisticsSearchBean;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyCertEditBean;
import com.joysuch.wwyt.bp.bean.BpWorkSafetyCertListBean.Search;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyCert;
import com.joysuch.wwyt.bp.repository.BpWorkSafetyCertDao;
import com.joysuch.wwyt.bp.service.BpWorkSafetyCertService;
import com.joysuch.wwyt.common.enums.TemplateTypes;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.util.PrintExportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/bp/work-safety-cert")
@Api(tags = "/bp/workSafetyCert安全作业证")
@Slf4j
public class BpWorkSafetyCertController {

    private static final Logger logger = LoggerFactory.getLogger(BpWorkSafetyCertController.class);

    @Autowired
    private BpWorkSafetyCertService bpWorkSafetyCertService;
    @Autowired
    private PrintExportUtil printExportUtil;
    @Autowired
    private BpWorkSafetyCertDao dao;

    @Value("${wwyt.file.upload.dir}")
    private String templateOutput;


    // @RequestMapping("restricted-space-add")
    // public Object add(@Valid BpWorkSafetyCertRestrictedSpaceEditBean entity) {
    // try {
    // bpWorkSafetyCertService.add(entity);
    // return ResultBean.success("");
    // } catch (Exception e) {
    // logger.error("创建失败", e);
    // return ResultBean.fail(101, "创建失败");
    // }
    // }

    @RequestMapping("update")
    public Object update(@Valid BpWorkSafetyCertEditBean entity) {
        try {
            if (entity.getId() == null) {
                return ResultBean.fail(102, "未指定主键");
            }
            // bpWorkSafetyCertService.update(entity);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("更新失败：#" + entity.getId(), e);
            return ResultBean.fail(101, "更新失败");
        }
    }

    @RequestMapping("page")
    public Object page(Pageable page, Search condition) {
        try {
            // Page<BpWorkSafetyCertListBean> data = bpWorkSafetyCertService.findByPage(page, condition);
            // return ResultBean.pageData(data.getContent(), data.getTotalElements());
            return ResultBean.pageData(Collections.EMPTY_LIST, 0);
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @RequestMapping("delete")
    public Object delete(Long id) {
        try {
            bpWorkSafetyCertService.delete(id);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

    @RequestMapping("get")
    public Object getById(@Valid @NotNull(field = "id") Long id) {
        try {
            return ResultBean.success(bpWorkSafetyCertService.getById(id));
        } catch (Exception e) {
            logger.error("查询详情失败", e);
            return ResultBean.fail(101, "查询详情失败:" + e.getMessage());
        }
    }

    /**
     * 风险点评估word下载
     */
    @RequestMapping("pointAssessmenPrint")
    @RequiresPermissions("bp:work-safety-cert:pointAssessmenPdfPrint")
    @ApiOperation(value = "作业证风险点评价word下载")
    public void pointAssessmenPrint(String code, HttpServletRequest request, HttpServletResponse response) {
        String outputFileName = UUID.randomUUID().toString();
        File wordFile = null;
        try {
            Map<String, Object> dataMap = bpWorkSafetyCertService.pointAssessmenPrint(code);
            String filename = templateOutput + "/" + outputFileName + ".docx";
            wordFile = new File(filename);
            FileOutputStream fos = new FileOutputStream(wordFile);
            byte[] doc = printExportUtil.exportWord(TemplateTypes.getFileName(100), dataMap);
            fos.write(doc);
            fos.flush();
            response.setContentType("application/msword;charset=UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        fileToStreamResult(wordFile, "word下载成功", response);
    }

    /**
     * 风险点评估pdf打印
     */
    @RequestMapping("pointAssessmenPdfPrint")
    @RequiresPermissions("bp:work-safety-cert:pointAssessmenPdfPrint")
    @ApiOperation(value = "作业证风险点评价PDF打印")
    public void pointAssessmenPDF(String code, HttpServletResponse response) {
        response.setContentType("application/pdf;charset=UTF-8");
        Map<String, Object> dataMap = bpWorkSafetyCertService.pointAssessmenPrint(code);
        File file = null;
        try {
            file = printExportUtil.generatePDF(dataMap, "workSafetyCertRiskEvalTemp");
            response.setContentType("application/pdf;charset=UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        fileToStreamResult(file, "pdf下载失败", response);
    }

    private void fileToStreamResult(File file, String message, HttpServletResponse response) {
        try {
            if (file.exists()) {
                byte[] cache = new byte[2048];
                int len = 0;
                FileInputStream fis = new FileInputStream(file);
                while ((len = fis.read(cache)) != -1) {
                    response.getOutputStream().write(cache, 0, len);
                }
                fis.close();
                response.getOutputStream().flush();
            }
        } catch (IOException e) {
            log.error(message, e);
        }
    }

    //作业证导出
    @RequestMapping("/safetyWordExpord")
    @ApiOperation(value = "作业证word打印")
    @RequiresPermissions("bp:work-safety-cert:safetyWordExpord")
    public void SimpleWordExport(HttpServletRequest request, HttpServletResponse response, Long id) throws IOException {
        BpWorkSafetyCert cert = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("作业证不存在"));
        try {
            Map<String, Object> map = bpWorkSafetyCertService.getSafetyMap(id, cert.getType());
            //获取模板名称
            String telepmentName = getTelepmentNameByType(cert.getType()).trim();
            InputStream stream = BpWorkSafetyApplyFireController.class.getClassLoader().getResourceAsStream("template" + File.separator + telepmentName);
            byte[] bytes = new byte[0];
            bytes = new byte[stream.available()];
            stream.read(bytes);
            XWPFDocument doc = WordExportUtil.exportWord07(
                    "template/" + telepmentName, map);
            String image = templateOutput + File.separator + telepmentName;
//            String image = "F:" + File.separator + "test" + File.separator + telepmentName;
            FileOutputStream fos = new FileOutputStream(image);
            doc.write(fos);
            fos.close();
            File imageFile = new File(image);
            response.setContentType(getContentType(imageFile));
            // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            // 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
            String filename = telepmentName;
            String agent = request.getHeader("User-Agent");
            if (agent.contains("MSIE")) {
                // IE浏览器
                filename = URLEncoder.encode(filename, "utf-8");
                filename = filename.replace("+", " ");
            } else {
                // 其它浏览器
                filename = URLEncoder.encode(filename, "utf-8");
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            if (imageFile.exists()) {
                byte[] cache = new byte[2048];
                int len = 0;
                FileInputStream fis = new FileInputStream(imageFile);
                while ((len = fis.read(cache)) != -1) {
                    response.getOutputStream().write(cache, 0, len);
                }
                fis.close();
                response.getOutputStream().flush();
            } else {
                response.setStatus(404);
                response.getOutputStream().flush();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 作业统计
     *
     * @param pageable
     * @return
     */
    @GetMapping("safetyStatistics")
    @ApiOperation(value = "作业证统计")
    public ResultBean safetyStatistics(Pageable pageable, BpSafetyStatisticsSearchBean condition) {
        return bpWorkSafetyCertService.safetyStatistics(pageable, condition);
    }

    //获取模板名称
    private String getTelepmentNameByType(String type) {
        if ("动火".equals(type)) {
            return "DH.docx";
        } else if ("受限空间".equals(type)) {
            return "SXKJ.docx";
        } else if ("高处".equals(type)) {
            return "GC.docx";
        } else if ("吊装".equals(type)) {
            return "DZ.docx";
        } else if ("临时用电".equals(type)) {
            return "LSYD.docx";
        } else if ("盲板抽堵".equals(type)) {
            return "MBCD.docx";
        } else if ("动土".equals(type)) {
            return "DT.docx";
        } else if ("断路".equals(type)) {
            return "DL.docx";
        } else {
            return null;
        }
    }


    private String getContentType(File imageFile) {
        return "multipart/form-data";
    }
}
